import React, { useState, useRef, useEffect } from 'react'
import { Tabs, Typography, Menu, Dropdown, Button, Space, message } from 'antd'
import { PlusOutlined, MoreOutlined } from '@ant-design/icons'
import EditableTable from './components/EditableTable.jsx'

import './App.css'

const { Title } = Typography

/**
 * 主应用组件
 * 提供多Tab页面管理和右键菜单功能
 */
function App() {
  const [activeKey, setActiveKey] = useState('')
  const [panes, setPanes] = useState([])
  const [loading, setLoading] = useState(true)
  const [tabChanges, setTabChanges] = useState({}) // 跟踪每个tab的变更状态
  const newTabIndex = useRef(1)

  /**
   * 从数据库加载城市数据作为Tab页面
   */
  useEffect(() => {
    const loadCities = async () => {
      try {
        const response = await fetch('http://localhost:3003/api/files')
        if (response.ok) {
          const files = await response.json()
          if (files.length > 0) {
            const cityPanes = files.map(file => ({
              title: file.name,
              content: <EditableTable 
                fileId={file.id} 
                onDataChange={(hasChanges) => handleTabDataChange(file.id.toString(), hasChanges)}
              />,
              key: file.id.toString(),
            }))
            setPanes(cityPanes)
            setActiveKey(cityPanes[0].key)
            newTabIndex.current = Math.max(...files.map(f => f.id)) + 1
          } else {
            // 如果没有数据，创建默认tab
            const defaultPane = {
              title: '默认城市',
              content: <EditableTable 
                onDataChange={(hasChanges) => handleTabDataChange('1', hasChanges)}
              />,
              key: '1',
            }
            setPanes([defaultPane])
            setActiveKey('1')
          }
        } else {
          message.error('加载城市数据失败')
        }
      } catch (error) {
        console.error('加载城市数据出错:', error)
        message.error('连接服务器失败')
        // 创建默认tab作为fallback
        const defaultPane = {
          title: '默认城市',
          content: <EditableTable />,
          key: '1',
        }
        setPanes([defaultPane])
        setActiveKey('1')
      } finally {
        setLoading(false)
      }
    }

    loadCities()
  }, [])

  /**
   * 处理tab数据变更状态
   */
  const handleTabDataChange = (tabKey, hasChanges) => {
    setTabChanges(prev => ({
      ...prev,
      [tabKey]: hasChanges
    }))
  }

  /**
   * 添加新的城市Tab页面
   */
  const add = async () => {
    const cityName = prompt('请输入新城市名称:', `城市${panes.length + 1}`)
    if (!cityName || !cityName.trim()) {
      return
    }

    try {
      // 创建新的城市文件
      const response = await fetch('http://localhost:3003/api/files', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name: cityName.trim() })
      })

      if (response.ok) {
        const newFile = await response.json()
        const newPane = {
          title: newFile.name,
          content: <EditableTable 
            fileId={newFile.id} 
            onDataChange={(hasChanges) => handleTabDataChange(newFile.id.toString(), hasChanges)}
          />,
          key: newFile.id.toString(),
        }
        const newPanes = [...panes, newPane]
        setPanes(newPanes)
        setActiveKey(newPane.key)
        message.success(`成功创建城市"${newFile.name}"的配置页面`)
      } else {
        const error = await response.json()
        message.error('创建城市失败: ' + (error.error || '未知错误'))
      }
    } catch (error) {
      console.error('创建城市失败:', error)
      message.error('创建城市失败: ' + error.message)
    }
  }

  /**
   * 删除城市Tab页面
   */
  const remove = async (targetKey) => {
    const targetPane = panes.find(pane => pane.key === targetKey)
    if (!targetPane) {
      return
    }

    const confirmed = window.confirm(`确定要删除城市"${targetPane.title}"吗？这将删除该城市的所有配置数据。`)
    if (!confirmed) {
      return
    }

    try {
      // 删除数据库中的城市文件
      const response = await fetch(`http://localhost:3003/api/files/${targetKey}`, {
        method: 'DELETE'
      })

      if (response.ok) {
        let newActiveKey = activeKey
        let lastIndex = -1
        panes.forEach((pane, i) => {
          if (pane.key === targetKey) {
            lastIndex = i - 1
          }
        })
        const newPanes = panes.filter((pane) => pane.key !== targetKey)
        if (newPanes.length && newActiveKey === targetKey) {
          if (lastIndex >= 0) {
            newActiveKey = newPanes[lastIndex].key
          } else {
            newActiveKey = newPanes[0].key
          }
        }
        setPanes(newPanes)
        setActiveKey(newActiveKey)
        message.success(`成功删除城市"${targetPane.title}"`)
      } else {
        const error = await response.json()
        message.error('删除城市失败: ' + (error.error || '未知错误'))
      }
    } catch (error) {
      console.error('删除城市失败:', error)
      message.error('删除城市失败: ' + error.message)
    }
  }

  /**
   * Tab页面编辑操作
   */
  const onEdit = (targetKey, action) => {
    if (action === 'add') {
      add()
    } else {
      remove(targetKey)
    }
  }

  /**
   * 重命名城市Tab页面
   */
  const renameTab = async (key, newTitle) => {
    if (!newTitle || !newTitle.trim()) {
      message.error('城市名称不能为空')
      return
    }

    try {
      // 更新数据库中的城市文件名
      const response = await fetch(`http://localhost:3003/api/files/${key}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name: newTitle.trim() })
      })

      if (response.ok) {
        const newPanes = panes.map(pane => 
          pane.key === key ? { ...pane, title: newTitle.trim() } : pane
        )
        setPanes(newPanes)
        message.success('重命名成功')
      } else {
        const error = await response.json()
        message.error('重命名失败: ' + (error.error || '未知错误'))
      }
    } catch (error) {
      console.error('重命名失败:', error)
      message.error('重命名失败: ' + error.message)
    }
  }

  /**
   * 复制城市Tab页面
   */
  const duplicateTab = async (key) => {
    const targetPane = panes.find(pane => pane.key === key)
    if (!targetPane) {
      return
    }

    const newCityName = `${targetPane.title}_副本`
    
    try {
      // 创建新的城市文件
      const createResponse = await fetch('http://localhost:3003/api/files', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name: newCityName })
      })

      if (!createResponse.ok) {
        const error = await createResponse.json()
        message.error('创建副本失败: ' + (error.error || '未知错误'))
        return
      }

      const newFile = await createResponse.json()

      // 获取原城市的配置数据
      const dataResponse = await fetch(`http://localhost:3003/api/files/${key}/data`)
      if (dataResponse.ok) {
        const originalData = await dataResponse.json()
        
        if (originalData.length > 0) {
          // 复制配置数据到新城市
          const copyData = originalData.map(item => ({
            sequence_number: item.sequence_number,
            type: item.type,
            start_addr: item.start_addr,
            data_type: item.data_type,
            variable: item.variable,
            description: item.description
          }))

          const saveResponse = await fetch(`http://localhost:3003/api/files/${newFile.id}/data`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(copyData)
          })

          if (!saveResponse.ok) {
            console.warn('复制配置数据失败，但城市创建成功')
          }
        }
      }

      // 添加新的tab
      const newPane = {
        title: newFile.name,
        content: <EditableTable fileId={newFile.id} />,
        key: newFile.id.toString(),
      }
      const newPanes = [...panes, newPane]
      setPanes(newPanes)
      setActiveKey(newPane.key)
      message.success(`成功复制城市"${targetPane.title}"为"${newFile.name}"`)
      
    } catch (error) {
      console.error('复制城市失败:', error)
      message.error('复制城市失败: ' + error.message)
    }
  }

  /**
   * 右键菜单配置
   */
  const getTabContextMenu = (key) => ([
    {
      key: 'rename',
      label: '重命名',
      onClick: () => {
        const newTitle = prompt('请输入新的Tab名称:', panes.find(p => p.key === key)?.title)
        if (newTitle && newTitle.trim()) {
          renameTab(key, newTitle.trim())
        }
      }
    },
    {
      key: 'duplicate',
      label: '复制',
      onClick: () => duplicateTab(key)
    },
    {
      type: 'divider'
    },
    {
      key: 'close',
      label: '关闭',
      disabled: panes.length === 1,
      onClick: () => remove(key)
    },
    {
      key: 'closeOthers',
      label: '关闭其他',
      disabled: panes.length === 1,
      onClick: () => {
        const newPanes = panes.filter(pane => pane.key === key)
        setPanes(newPanes)
        setActiveKey(key)
        message.success('已关闭其他Tab页面')
      }
    }
  ])

  /**
   * 自定义Tab标题，支持右键菜单
   */
  const renderTabBar = (props, DefaultTabBar) => (
    <DefaultTabBar {...props}>
      {(node) => {
        const key = node.key
        return (
          <Dropdown
            menu={{ items: getTabContextMenu(key) }}
            trigger={['contextMenu']}
            key={key}
          >
            <div onContextMenu={(e) => e.preventDefault()}>
              {node}
            </div>
          </Dropdown>
        )
      }}
    </DefaultTabBar>
  )

  return (
    <div style={{ margin: 0, padding: '16px', width: '100%', boxSizing: 'border-box' }}>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={2} style={{ margin: 0 }}>可编辑配置表格管理系统</Title>
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={add}>
            新增城市
          </Button>
        </Space>
      </div>
      
      <Tabs
        type="editable-card"
        onChange={setActiveKey}
        activeKey={activeKey}
        onEdit={onEdit}
        renderTabBar={renderTabBar}
        items={panes.map(pane => ({
          key: pane.key,
          label: `${pane.title}${tabChanges[pane.key] ? ' *' : ''}`,
          children: pane.content,
          closable: panes.length > 1
        }))}
        style={{ minHeight: '500px', margin: 0 }}
      />
    </div>
  )
}

export default App
